# -*- coding:utf-8 -*-

from typing import NoReturn, Union, Literal

__all__ = ('MatchLocation', 'LocationListT', 'OCRLocationList', 'ListLocation', 'OCRLocationListHandle',
           'OCREngines', 'SupportedOCREngines')


MatchLocation = tuple[float, float]

LocationListT = list[float, float]

SupportedOCREngines = ['easyocr', 'paddleocr']

OCREngines = Literal['easyocr', 'paddleocr']

OCRLocationList = Union[list[list[float, float]], list[LocationListT], list[MatchLocation], list[list[float]]]


class ListLocation:

    def __init__(self, location_list: LocationListT) -> NoReturn:
        self._l_list = location_list
        self.x = self._l_list[0]
        self.y = self._l_list[1]

    def __lt__(self, other):
        if self.x == other.x:
            return self.y < other.y
        else:
            return self.x < other.x

    def __repr__(self):
        return f'LocationListT({self._l_list})'

    def __iter__(self):
        return iter(self._l_list)
    
    def __eq__(self, other) -> bool:
        # 坐标的 x、y都相等，则认为两个坐标相等
        return self.x == other.x and self.y == other.y
    
    def __le__(self, other) -> bool:
        # 小于等于符号，需要单独写一个方法，因为python中不支持自动识别 <=
        return self.__lt__(other) or self.__eq__(other)    


class OCRLocationListHandle:

    def __init__(self, list_location_list: OCRLocationList):
        self._l_list = list_location_list

    def merge_location_by_x(self, threshold: float = 0.1) -> OCRLocationList:
        pass

    def merge_location_by_y(self, threshold: float = 0.1) -> OCRLocationList:
        pass

    def sort_and_get_centre_location(self) -> tuple[float, float]:
        """
        根据坐标的x、y排序，并计算返回中心坐标
        Returns:
            res_tuple(tuple[float, float]): 中心坐标

        """
        loc_list = list(self._l_list)
        loc_list.sort()
        res_x = ListLocation(loc_list[0]).x + ListLocation(loc_list[-1]).x
        res_y = ListLocation(loc_list[0]).y + ListLocation(loc_list[-1]).y
        res_tuple = (res_x / 2, res_y / 2)
        return res_tuple


if __name__ == '__main__':
    # [[171.0, 85.0], [269.0, 85.0], [269.0, 102.0], [171.0, 102.0]]
    test_list = [[171.0, 85.0], [269.0, 85.0], [269.0, 102.0], [171.0, 102.0]]
    l_list = OCRLocationListHandle(test_list)
    s_tup = l_list.sort_and_get_centre_location()
    print(s_tup)
